package com.linln.admin.pcs.controller;


import com.linln.admin.pcs.service.NotificationMiddleService;
import com.linln.admin.pcs.service.VerifyLogService;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ValidationUtil;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 合同模板管理
 */
@Controller
@RequestMapping("/pcs/contractTpl")
public class ContractTplController {

    @Autowired
    private AppService appService;
    @Autowired
    private  ProjectRepository projectRepository;
    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private ContractTplRepository contractTplRepository;

    @Autowired
    private VerifyLogService verifyLogService;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private NotificationMiddleService notificationMiddleService;
    @Autowired
    private UserRepository userRepository;

    /**
     * 合同模板页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:contractTpl:index")
    public ResponseEntity<?> index(Model model, @EntityParam ContractTpl contractTpl) {
        return appService.layTable(contractTplRepository, before -> {
                    model.addAttribute("verifyStatus", HttpServletUtil.getParameter("verifyStatus",""));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("sn", QuerySpec.LIKE)
                            .withMatcher("title", QuerySpec.LIKE)
                            .withMatcher("verifyStatus", QuerySpec.EQUAL);
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/contract_tpl/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
//                    pageResult.getContent().forEach(item -> {
//                        ContractTpl data = (ContractTpl) item;
//                        QuerySpec querySpec = QuerySpec.matching();
//                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, String.valueOf(data.getId()))
//                                .withMatcherValue("status", QuerySpec.EQUAL, String.valueOf(1));
//                        Specification<Porter> specification = QuerySpec.of(querySpec);
//                        data.setPorterNum(porterRepository.count(specification));
//                        item = data;
//                    });
                }

        );

    }


    /**
     * 表单
     */
    @RequestMapping("/form")
    @RequiresPermissions("pcs:contractTpl:add")
    public ResponseEntity<?> form(Model model, @EntityParam ContractTpl contractTpl, HttpServletRequest request) throws Exception {

        return appService.form(contractTplRepository, "/pcs/contract_tpl/form",
                (isEdit) -> {

                    return model;

                },
                (isEdit, vo) -> {

                    model.addAttribute("vo", vo);
                    // 你可以在这里添加其他逻辑
                    return model;
                },
                (data) -> {
                    // 保存前数据校验
                    List<ValidationUtil.ValidationRule<?>> rules = new ArrayList<>();
                    // 添加邮箱的校验规则
                    //            rules.add(new ValidationUtil.ValidationRule<>(
                    //                    porter.getCardNo(),
                    //                    email -> email != null ,
                    //                    "Email格式不正确"
                    //            ));

                    // 执行校验
                    return ValidationUtil.validateFields(rules);

                },
                (data) -> {

                    // 数据处理
                    if(contractTpl.getId() != null){
                        ContractTpl origin = contractTplRepository.getById(contractTpl.getId());
                        contractTpl.setStatus(origin.getStatus());
                        contractTpl.setCreateUser(origin.getCreateUser());
                        contractTpl.setCreateTime(origin.getCreateTime());
                    }
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        contractTpl.setCompanyId(companyId);
                        contractTpl.setCompanyName(user.getCompanyName());
                    }
                    contractTpl.setVerifyStatus(0);
                    contractTpl.setStatus((byte) 1);
                    // 解码 content
                    if (contractTpl.getContent() != null) {
                        try {
                            contractTpl.setContent(URLDecoder.decode(contractTpl.getContent(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return contractTpl;
                },

                (data) -> {
                    // 保存后续逻辑在这写
                    //推送数据到中台
                    ContractTpl d = (ContractTpl) data;
                    String content = "您有一个合同【"+d.getTitle()+"】需要审核，请及时处理";
                    QuerySpec querySpecUser = QuerySpec.matching();
                    querySpecUser.withMatcherValue("type", QuerySpec.EQUAL, "0");
                    List<User> userList = userRepository.findAll(QuerySpec.of(querySpecUser));
                    userList.forEach(user -> {
                        notificationMiddleService.send(content,  "/pcs/project/index?verifyStatus=0", user.getMiddleUserId(), request);
                    });
                });

    }


    @RequestMapping("/detail")
    public String detail(@RequestParam Long id, Model model) throws Exception{
        ContractTpl contractTpl = contractTplRepository.getById(id);
        model.addAttribute("vo",contractTpl);
        return "/pcs/contract_tpl/detail";
    }
    /**
     * 修改状态
     * @param model
     * @param contractTpl
     * @return
     * @throws Exception
     */
    @RequestMapping("/state")
    @RequiresPermissions("pcs:contractTpl:state")
    public ResponseEntity<?> state(Model model, @EntityParam ContractTpl contractTpl) throws Exception {

        return appService.save(contractTplRepository, (data) -> {

            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());

        }, (data) -> {
            // 处理数据
            ContractTpl origin = contractTplRepository.getById(contractTpl.getId());
            origin.setStatus(contractTpl.getStatus());

            return origin;

        }, (data) -> {
            // 更新后操作
        });

    }

    /**
     * 项目审核
     * @return
     * @throws Exception
     */
    @RequestMapping("/verify")
    @RequiresPermissions("pcs:contractTpl:verify")
    public ResponseEntity<?> verify() throws Exception {

        String ids = HttpServletUtil.getParameter("ids");
        Integer verifyStatus = HttpServletUtil.getParameterInt("verifyStatus");
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        idList.forEach(item -> {
            ContractTpl contractTpl = contractTplRepository.getById(item);
            contractTpl.setVerifyStatus(verifyStatus);
            verifyLogService.setVerifyLog(item, verifyStatus,2,"");
            contractTplRepository.save(contractTpl);
        });
        return ResponseEntity.ok(ResultVoUtil.success("成功"));

    }


    //权限审核
    @RequestMapping("/canal")
    @RequiresPermissions("pcs:contractTpl:verify")
    public ResponseEntity<?> canal(Model model, @EntityParam ContractTpl contractTpl) {
        String method = HttpServletUtil.getMethod();
        if (method.equals("GET")) {
            String id = HttpServletUtil.getParameter("id");
            Integer verifyStatus = HttpServletUtil.getParameterInt("verifyStatus");
            model.addAttribute("id", id);
            model.addAttribute("verifyStatus", verifyStatus);
            // 必须手动渲染模板
            Context context = new Context();
            // 将数据加入到 Thymeleaf 上下文中
            context.setVariables(model.asMap());
            // 使用 Thymeleaf 渲染模板
            StringWriter writer = new StringWriter();
            thymeleafViewResolver.getTemplateEngine().process("/pcs/contract_tpl/verify", context, writer);

            return ResponseEntity.ok( writer.toString());
        }else{
            ContractTpl contractTpl1 = contractTplRepository.getById(contractTpl.getId());
            String remark = "";

            if(contractTpl.getRemark()!=null){
                //驳回权限申请
                remark = contractTpl.getRemark();
                contractTpl1.setRemark(contractTpl.getRemark());
            }

            contractTpl1.setVerifyStatus(contractTpl.getVerifyStatus());
            verifyLogService.setVerifyLog(contractTpl.getId(), contractTpl.getVerifyStatus(),1,remark);
            contractTplRepository.save(contractTpl1);
            return ResponseEntity.ok(ResultVoUtil.success("成功"));
        }

    }







}
